<template>
  <div class="xh-user">
    <div class="xh-user__hd">员工</div>
    <div class="xh-user__bd">
      <el-autocomplete v-model="searchInput"
                       :disabled="disabled"
                       :popper-append-to-body="false"
                       :fetch-suggestions="searchListUser"
                       placeholder="请输入内容"
                       @select="searchSelect">
        <template #default="{ item }">
          <span>{{ item[config.label] }}</span>
          <span style="color: #999;">{{
              `(${item.deptName || ''}${item.deptName ? '-' : ''}${item.post || '无'})`
            }}</span>
        </template>
      </el-autocomplete>
      <div class="search-list">
        <el-breadcrumb v-if="breadcrumbList.length > 0 && !config.isList"
                       style="padding: 5px 0;"
                       separator-class="el-icon-arrow-right">
          <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index">
            <a href="javascript:;" @click="breadcrumbBtn(item, index)">{{ item.label }}</a>
          </el-breadcrumb-item>
        </el-breadcrumb>

        <div v-if="currentBreadcrumbItem" class="xh-user__list">
          <el-checkbox v-if="!radio" v-model="allChecked"
                       :disabled="disabled"
                       style="line-height: 30px;"
                       @change="handleCheckAllChange">全选
          </el-checkbox>
          <WkDepCheckbox :radio="radio"
                         :data-list="currentBreadcrumbItem.deptList"
                         :props="props"
                         :disabled="disabled"
                         only-show
                         @childrenClick="childrenDebounceClick"/>

          <WkUserCheckbox ref="userCheckboxRef" :radio="radio" :disabled="disabled"
                          :props="props"
                          :dataList="currentBreadcrumbItem.employeeList"
                          :selectedDataList="userSelectedList"
                          @selectedChange="checkboxChange"
                          @allSelectFlagChange="onAllSelect"/>
        </div>
      </div>
    </div>
    <div class="xh-user__ft">
      <span class="select-info">已选择<span class="select-info--num">
        {{ userSelectedList ? userSelectedList.length : 0 }}
      </span>
        项
      </span>
      <el-button link @click="clearAll">清空</el-button>
    </div>
  </div>
</template>

<script setup>
import {
  adminUserQueryByDeptAPI
} from '/src/api/admin/user.js'
import {
  hrmEmployeeQueryInAPI,
  hrmEmployeeQueryByDeptAPI
} from '/src/api/hrm/employee.js'
import {userListAPI} from '/src/api/common.js'

import WkDepCheckbox from '../../WkDepSelect/src/WkDepCheckbox.vue'
import WkUserCheckbox from './WkUserCheckbox.vue'

import PinyinMatch from 'pinyin-match'
import merge from '/src/utils/merge.js'
import {debounce} from 'throttle-debounce'

const DefaultWkUser = {
  value: 'userId',
  label: 'realname',
  // 默认的搜索人资和管理端人员请求
  dataType: 'manage', // 部门的 value label 一致，用 dataType 区分 manage hrm,
  isList: false // 默认是树形接口，如果是列需设置为true
}

defineOptions({
  name: 'WkUser', // 新建 user
  inheritAttrs: false,
})

const properties = defineProps({
  radio: Boolean,
  userOptionList: Array,
  userSelectedList: Array,
  // 取值字段
  props: {
    type: Object,
    default: () => {
      return {}
    }
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const optionData = reactive({
  searchInput: '',
  searchUserList: [],

  // 面包头
  breadcrumbList: [],

  // 当前面包屑
  currentBreadcrumbItem: null,
  // 全选
  allChecked: false,
})

const {
  searchInput, breadcrumbList,
  currentBreadcrumbItem, allChecked
} = toRefs(optionData)


const emits = defineEmits(['update:userSelectedList'])


const config = computed(() => {
  return merge({...DefaultWkUser}, properties.props || {})
})


watch(() => optionData.breadcrumbList, () => {
  if (!config.value.isList) {
    optionData.currentBreadcrumbItem = optionData.breadcrumbList[optionData.breadcrumbList.length - 1]
  }
}, {
  deep: true
})

watch(() => properties.userOptionList, () => {
  if (config.value.isList) {
    optionData.currentBreadcrumbItem = {
      employeeList: properties.userOptionList
    }
  }
}, {
  immediate: true
})

let childrenDebounceClick = () => {
}

function created() {
  if (!config.value.isList) {
    getDepUserList(0)
    childrenDebounceClick = debounce(300, childrenClick)
  } else {
    childrenDebounceClick = () => {
    }
  }
}

created()

/**
 * 获取搜索请求
 * 根据列表请求对应获取，如果 props searchParams 有值，以 searchParams 为准
 */
function getSearchRequest() {
  // 人资的默认搜索接口
  if (config.value.dataType === 'hrm') {
    return hrmEmployeeQueryInAPI
  }

  return userListAPI
}

/**
 * 列效果进行搜索
 */
function searchListUser(queryString, cb) {
  if (optionData.searchUserList && optionData.searchUserList.length || properties.userOptionList) {
    const searchUserList = properties.userOptionList || optionData.searchUserList
    if (queryString) {
      cb(searchUserList.filter(item => PinyinMatch.match(item[config.value.label] || '', queryString) || PinyinMatch.match(item.deptName || '', queryString)))
    } else {
      cb(searchUserList)
    }
  } else {
    const request = getSearchRequest()
    let params = {pageType: 0}
    request(params).then(res => {
      const resData = res.data.data
      optionData.searchUserList = resData.hasOwnProperty('list') ? (resData.list || []) : (resData || [])
      if (queryString) {
        cb(optionData.searchUserList.filter(item => PinyinMatch.match(item[config.value.label] || '', queryString)))
      } else {
        cb(optionData.searchUserList)
      }
    }).catch(() => {
    })
  }
}


/**
 * 搜索选择
 */
function searchSelect(item) {
  userCheckboxRef.value.searchSelect(item)
}

/**
 * 勾选
 */
function checkboxChange(val) {
  if (properties.radio) {
    // emits('input', val.length ? [val[val.length - 1]] : [])

    // 单选直接关闭窗口
    // emits('close')
  } else {
    // emits('input', val)
  }

  nextTick(() => {
    emitUserSelectedList(val)
  })
}

function emitUserSelectedList(val) {
  emits('update:userSelectedList', val)
}

const userCheckboxRef = ref()

/**
 * 全部勾选
 */
function handleCheckAllChange(val) {
  if (userCheckboxRef.value) {
    userCheckboxRef.value.handleCheckAllChange(val)
  }
}

/**
 * 用户全选
 */
function onAllSelect(allChecked) {
  if (optionData.allChecked != allChecked) {
    optionData.allChecked = allChecked
  }
}

/**
 * 清空全部
 */
function clearAll() {
  emitUserSelectedList([])
}

/**
 * 获取部门员工数据
 */
function getDepUserList(deptId, depInfo) {
  const request = config.value.dataType === 'hrm' ? hrmEmployeeQueryByDeptAPI : (adminUserQueryByDeptAPI)
  request(deptId).then(res => {
    console.log("res", res)
    console.log("res", res.data.data)
    const data = res.data.data || {}
    const deptList = data.deptList || []

    // employeeList 人资  userList 系统管理
    const employeeList = data.employeeList || data.userList || []

    if (deptId == 0) {
      optionData.breadcrumbList = [{label: '全部', deptList: deptList, employeeList: employeeList}]
    } else {
      optionData.breadcrumbList.push({label: depInfo.name, deptList: deptList, employeeList: employeeList})
    }
  }).catch(() => {
  })
}

/**
 * 下一级
 */
function childrenClick(item) {
  if (!properties.radio) {
    optionData.allChecked = false
  }
  getDepUserList(item.deptId, item)
}


/**
 * 面包屑点击
 */
function breadcrumbBtn(item, index) {
  if (index + 1 <= optionData.breadcrumbList.length - 1) {
    optionData.breadcrumbList.splice(index + 1, optionData.breadcrumbList.length - 1)
  }
}


</script>


<script type="text/javascript">


export default {

  components: {
    // WkDepCheckbox,
    // WkUserCheckbox
  },

  props: {},
  data() {
    return {}
  },
  computed: {},
  watch: {},

  methods: {}
}
</script>
<style lang="scss" scoped>
/* 选择员工 */

.search-list {
  padding: 5px 0;
  height: 248px;
  overflow: auto;
}

.xh-user {
  color: #333;
  font-size: 13px;

  &__hd {
    padding: 0 15px;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #e6e6e6;
  }

  &__bd {
    padding: 10px 12px;
  }

  &__ft {
    padding: 5px 12px;
    background: #f7f8fa;
    border-top: 1px solid #e6e6e6;

    .el-button {
      font-size: 12px;
    }
  }

  &__list {
    height: calc(100% - 24px);
    overflow-y: auto;
    padding-left: 5px;
  }
}

// 选择信息
.select-info {
  display: inline-block;
  width: calc(100% - 30px);

  &--num {
    color: #2362FB;
  }
}

// check样式
.el-checkbox-group {
  overflow-x: hidden;
}

.el-checkbox {
  :deep(.el-checkbox__label) {
    color: #333;
  }
}

.all-check {
  display: inline-block;
  padding: 5px 0;
}

.el-autocomplete {
  width: 100%;

  :deep(.el-input__inner) {
    background-color: #F4F4F4;
    border: none;
  }
}
</style>
